import {
  BadRequestException,
  ConflictException,
  Injectable,
  InternalServerErrorException,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import {
  CartDto,
  CollectDto,
  GetCartDto,
  GetCollectDto,
} from "../dto/operate.dto";
import { Goods } from "/@/entities/goods/Goods.entity";
import { Cart } from "/@/entities/operate/Cart.entity";
import { Collect } from "/@/entities/operate/Collect.entity";
import { Swiper } from "/@/entities/operate/Swiper.entity";
import { format } from "/@/utils/moment";
@Injectable()
export class WeappOperateService {
  constructor(
    @InjectRepository(Cart)
    private cartRepository: Repository<Cart>,
    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>,
    @InjectRepository(Swiper)
    private swiperRepository: Repository<Swiper>,
    @InjectRepository(Collect)
    private collectRepository: Repository<Collect>,
  ) {
    //
  }
  /**
   * 获取轮播图商品分类
   * @param params 字段
   */
  async getSwiperList() {
    try {
      let qb = this.swiperRepository.createQueryBuilder("swiper");
      qb = qb
        .orderBy("swiper.update_at", "DESC")
        .where("swiper.status = :status", { status: "1" });
      const data = await qb.getMany();
      return data;
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  // 收藏相关
  /**
   * 获取用户收藏商品
   * @param params 字段
   */
  async getCollectList(query: GetCollectDto, user: any) {
    const { pageSize = 20, page = 1 } = query;
    const { id: user_id } = user;
    try {
      const [items, total] = await this.goodsRepository
        .createQueryBuilder("goods")
        .andWhere((qb) => {
          const subQuery = qb
            .subQuery()
            .from("collect", "collect")
            .select("collect.goods_id")
            .where("collect.user_id = :user_id")
            .orderBy("collect.update_at", "ASC")
            .getQuery();
          return "goods.id in " + subQuery;
        })
        .skip(pageSize * (page - 1))
        .take(pageSize)
        .setParameter("user_id", user_id)
        .getManyAndCount();
      return { items, total };
    } catch (error) {
      console.log(error);
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 用户添加收藏商品
   * @param params 字段
   */
  async addCollect(param: CollectDto, user: any) {
    try {
      const { goods_id } = param;
      const { id: user_id } = user;
      const collect = await this.collectRepository.findOne({
        goods_id,
        user_id,
      });
      if (collect) {
        throw new ConflictException("重复添加收藏");
      }
      //新增商品分类
      const entity = this.collectRepository.create({ goods_id, user_id });
      await this.collectRepository.save(entity);
      return "ok";
    } catch (error) {
      throw new InternalServerErrorException("添加收藏失败");
    }
  }

  /**
   * 用户删除收藏商品
   * @param params 字段
   */
  async delCollect(param: CollectDto, user: any) {
    try {
      const { goods_id } = param;
      const { id: user_id } = user;
      const collect = await this.collectRepository.findOne({
        goods_id,
        user_id,
      });
      const data = await this.collectRepository.delete({ id: collect.id });
      if (data.affected === 0) {
        throw new BadRequestException("没有该收藏记录");
      }
      return "ok";
    } catch (error) {
      throw new InternalServerErrorException(error.response || "删除收藏失败");
    }
  }

  // 购物车相关
  /**
   * 获取用户购物车列表
   * @param query 字段
   */
  async getCartList(query: GetCartDto, user: any) {
    const { pageSize = 20, page = 1 } = query;
    const { id: user_id } = user;
    try {
      let qb = this.cartRepository.createQueryBuilder("cart");
      qb = qb
        .limit(pageSize)
        .offset((page - 1) * pageSize)
        .where("cart.user_id = :user_id", { user_id })
        .andWhere("cart.status = :status", { status: "1" })
        .leftJoinAndSelect(Goods, "goods", "goods.id = cart.goods_id")
        .select(
          `cart.id as id,
          cart.status as status,
          cart.update_at as update_at,
          cart.goods_id as goods_id,
          cart.goods_num as goods_num,
          goods.name as goods_name,
          goods.brief as goods_brief,
          goods.price as goods_price,
          goods.urls as goods_urls,
          goods.status as goods_status`,
        );
      const items = await qb.getRawMany();
      items.map((item) => {
        item.goods_urls = item.goods_urls.split(",");
        item.update_at = format(item.update_at, "YYYY-MM-DD HH:mm:ss");
        return item;
      });
      const total = await qb.getCount();
      return { items, total };
    } catch (error) {
      throw new InternalServerErrorException(error.response || "查询失败");
    }
  }

  /**
   * 用户添加、增加数量、删除 购物车
   * @param params 字段
   */
  async changeCart(param: CartDto, user: any) {
    try {
      const { goods_id, mode = "add" } = param;
      const { id: user_id } = user;
      let cart: any = null;

      // 根据用户以及商品
      cart = await this.cartRepository
        .createQueryBuilder("cart")
        .where("cart.goods_id = :goods_id", { goods_id })
        .andWhere("cart.user_id = :user_id", { user_id: user_id.toString() })
        .andWhere("cart.status = :status", { status: "1" })
        .getOne();

      if (cart) {
        const { id } = cart;
        // 判断是增是减，减时保证不低于1
        if (mode === "add") {
          cart.goods_num++;
        } else {
          // 如果只有一个还减，则删除
          if (cart.goods_num === 1) {
            await this.cartRepository.delete({ id });
            return "删除成功";
          }
          // 否者正常减少一个
          cart.goods_num--;
        }

        await this.cartRepository.update(id, cart);
        return "添加成功";
      }
      //新增购物车 数量默认是1
      const entity = this.cartRepository.create({
        goods_id,
        goods_num: 1,
        user_id,
      });
      await this.cartRepository.save(entity);
      return "ok";
    } catch (error) {
      console.log(error);
      throw new InternalServerErrorException(error.response || "操作失败");
    }
  }
}
